package net.lainiao.morethread.Chapter3.demo4;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * Created by Administrator on 2017/3/1.
 */
public class Searcher implements Runnable {
    private int firstRow;
    private int lastRow;
    private MatrixMock mock;
    private Result result;
    private int number;
    private final CyclicBarrier barrier;

    public Searcher(int firstRow, int lastRow, MatrixMock mock, Result result, int number, CyclicBarrier barrier) {
        this.firstRow = firstRow;
        this.lastRow = lastRow;
        this.mock = mock;
        this.result = result;
        this.number = number;
        this.barrier = barrier;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"分配到这个对象的行:Start"+firstRow+"End:"+lastRow);
        for (int i = firstRow; i <lastRow ; i++) {
            int counter=0;
            int[] row=mock.getRow(i);
            for (int j = 0; j < row.length; j++) {
                if(row[j]==number){
                    counter++;
                }
            }
            result.setData(i,counter);
        }
        System.out.println(Thread.currentThread().getName()+"分配到这个对象的行已经搜索完毕");
        try {
            //通知barrier该线程上的任务已经完成
            barrier.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        }
    }
}
